package store.aixx.jwt.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author yukai
 * @since 2021年12月11日 21:54
 */
@RequiredArgsConstructor
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;

    private final Environment environment;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(0, mappingJackson2HttpMessageConverter);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        if (environment.acceptsProfiles(Profiles.of("prod"))){
            registry.addMapping("/**")
                    .allowedHeaders("*")
                    .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                    .exposedHeaders("X-Authentication")
                    .allowedOrigins("http://aixx.store")
            ;
        }else{
            registry.addMapping("/**")
                    .allowedHeaders("*")
                    .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                    .exposedHeaders("X-Authentication")
                    .allowedOrigins("*")
            ;
        }
    }
}
